package com.jfs.session;

import com.jfs.zlk.util.SsrcUtil;

import javax.sip.ClientTransaction;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Description 视频流session管理器，管理视频预览、预览回放的通信句柄
 * @E-mail cwm3412638@163.com
 * @Author cwm
 * @Date 2022-08-23
 */
public class VideoStreamSessionManager {
    public final static ConcurrentHashMap<String, ClientTransaction> SESSION_MAP = new ConcurrentHashMap<>();
    public final static ConcurrentHashMap<String, String> SSRC_MAP = new ConcurrentHashMap<>();

    public final static ConcurrentHashMap<String, String> CHANNEL_MAP = new ConcurrentHashMap<>();
    public final static ConcurrentHashMap<String, String> STREAM_AND_CHANNEL = new ConcurrentHashMap<>();
    public final static ConcurrentHashMap<String, Integer> STREAM_AND_PORT = new ConcurrentHashMap<>();

    public static String createPlaySsrc() {
        return SsrcUtil.getPlaySsrc();
    }

    public static void put(String streamId, String ssrc, ClientTransaction transaction, String channelId,Integer port) {
        SESSION_MAP.put(streamId, transaction);
        SSRC_MAP.put(streamId, ssrc);
        CHANNEL_MAP.put(channelId, streamId);
        STREAM_AND_CHANNEL.put(streamId, channelId);
        STREAM_AND_PORT.put(streamId,port);
    }

    public static ClientTransaction get(String streamId) {
        if (SESSION_MAP.containsKey(streamId)) {
            return SESSION_MAP.get(streamId);
        }
        return null;
    }

    public static void remove(String streamId, String channelId) {
        SESSION_MAP.remove(streamId);
        SsrcUtil.releaseSsrc(SSRC_MAP.get(streamId));
        SSRC_MAP.remove(streamId);
        CHANNEL_MAP.remove(channelId);
        STREAM_AND_CHANNEL.remove(streamId);
    }

    public static String getStreamId(String channelId) {
        if (CHANNEL_MAP.containsKey(channelId)) {
            return CHANNEL_MAP.get(channelId);
        }
        return null;
    }

    public static String getSsrc(String streamId) {
        if (SSRC_MAP.containsKey(streamId)) {
            return SSRC_MAP.get(streamId);
        }
        return null;
    }

    public static String getChannelId(String streamId) {
        if (STREAM_AND_CHANNEL.containsKey(streamId)) {
            return STREAM_AND_CHANNEL.get(streamId);
        }
        return null;
    }
    public static Integer  getPortByChannel(String streamId){
        if (STREAM_AND_PORT.containsKey(streamId)){
            Integer integer = STREAM_AND_PORT.get(streamId);
            STREAM_AND_PORT.remove(streamId);
            return integer;
        }
        return null;
    }
}
